package com.member.mp.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.member.common.core.domain.R;
import com.member.shop.domain.SysBizGoods;
import com.member.shop.domain.SysBizOrder;
import com.member.shop.domain.SysBizOrderGoods;
import com.member.shop.dto.AlipayDto;
import com.member.shop.service.IAlipayService;
import com.member.shop.service.ISysBizGoodsService;
import com.member.shop.service.ISysBizOrderGoodsService;
import com.member.shop.service.ISysBizOrderService;
import com.member.shop.vo.AlipayBodyInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 支付宝接口
 * @ClassName AlipayController
 * @Date 2025/2/24 
 * @author luo.yun
 */
@Slf4j
@RestController
@Api(value = "支付宝接口", tags = {"支付宝接口"})
@RequestMapping("/wx/alipay")
public class AlipayController {

    @Resource
    private ISysBizOrderService sysBizOrderService;
    @Resource
    private IAlipayService alipayService;
    @Resource
    private ISysBizOrderGoodsService sysBizOrderGoodsService;
    @Resource
    private ISysBizGoodsService goodsService;

    /**
     * 创建订单
     */
    @PostMapping("/createOrder")
    public R<AlipayBodyInfo> createOrder(@RequestBody AlipayDto dto) {
        try {
            log.info("-------------- createOrder111 ------------AlipayDto:{}",dto.toString());
            AlipayBodyInfo vo = new AlipayBodyInfo();
            // 1、验证订单是否存在
            List<SysBizOrder> sysBizOrders = sysBizOrderService.list(new LambdaQueryWrapper<SysBizOrder>().eq(SysBizOrder::getPaymentId, dto.getPaymentId()));
            SysBizOrder sysBizOrder = null;
            if (!CollectionUtils.isEmpty(sysBizOrders)) {
                sysBizOrder = sysBizOrders.get(0);
            }
            if (sysBizOrder == null) {
                log.info("{}:订单为空", dto.getPaymentId());
                return R.fail("未查询到订单");
            }

            List<SysBizOrderGoods> list = sysBizOrderGoodsService.list(new LambdaQueryWrapper<SysBizOrderGoods>()
                    .eq(SysBizOrderGoods::getOrderId, sysBizOrder.getId()));

            List<Long> ids = list.stream().map(SysBizOrderGoods::getGoodsId).distinct().collect(Collectors.toList());

            List<SysBizGoods> goodsList = goodsService.list(new LambdaQueryWrapper<SysBizGoods>().in(SysBizGoods::getId, ids));
            if (!org.springframework.util.CollectionUtils.isEmpty(goodsList)) {
                // 获取下架商品名称列表
                List<String> offShelfNames = goodsList.stream()
                        .filter(g -> g.getGrounding() == 1)
                        .map(SysBizGoods::getName)
                        .collect(Collectors.toList());

                if (!offShelfNames.isEmpty()) {
                    return R.fail("存在已下架的商品：" + String.join("，", offShelfNames) + "，请重新调整商品");
                }
            }


            // 2、创建支付宝订单
            String orderStr = alipayService.createOrder(sysBizOrders.get(0).getTenantId(),dto.getPaymentId(), dto.getActualPaymentAmount(), dto.getOrderCode());
            vo.setBody(orderStr);
            log.info("-------------- createOrder ------------orderStr:{}",orderStr);
            return R.ok(vo);
        } catch (Exception e) {
            return R.fail("订单生成失败");
        }
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        // 验证签名
        boolean flag = alipayService.rsaCheckV1(request);
        if (flag) {
            String tradeStatus = request.getParameter("trade_status"); // 交易状态
            String outTradeNo = request.getParameter("out_trade_no"); // 商户订单号
            String tradeNo = request.getParameter("trade_no"); // 支付宝订单号
            log.info("-------------- notify------------tradeStatus:{},outTradeNo:{},tradeNo:{}",tradeStatus,outTradeNo,tradeNo);
            /**
             * 还可以从request中获取更多有用的参数，自己尝试
             */
            boolean notify = alipayService.notify(tradeStatus, outTradeNo, tradeNo);
            log.info("-------------- notify2------------notify:{}",notify);
            if(notify){
                return "success";
            }
        }
        return "fail";
    }

    /**
     * 支付宝充值回调
     * @param request request请求
     * @return 成功or失败
     */
    @PostMapping("/notifyBySurplus")
    public String notifyBySurplus(HttpServletRequest request) {
        // 验证签名
        boolean flag = alipayService.rsaCheckV1(request);
        if (flag) {
            String tradeStatus = request.getParameter("trade_status"); // 交易状态
            String outTradeNo = request.getParameter("out_trade_no"); // 商户订单号
            String tradeNo = request.getParameter("trade_no"); // 支付宝订单号
            log.info("-------------- notify------------tradeStatus:{},outTradeNo:{},tradeNo:{}",tradeStatus,outTradeNo,tradeNo);
            /**
             * 还可以从request中获取更多有用的参数，自己尝试
             */
            boolean notify = alipayService.notifyBySurplus(tradeStatus, outTradeNo, tradeNo);
            log.info("-------------- notify2------------notify:{}",notify);
            if(notify){
                return "success";
            }
        }
        return "fail";
    }

}
